local Signal = oopsys.getcls("Signal")

local area = class("WorldSceneArea",Signal){
    -- clients = {}, --服务端才有
    x = 0,
    y = 0,
    ix = 0,
    iy = 0,
    objects = {},
    tiles = {},
}

function area:__init__(ix,iy)
    if core.core_mode == CORE_MODE_SERVER then
        self.clients = {}
    end
    self.ix = ix or 0
    self.iy = iy or 0
    self.x = self.ix * WORLD_AREA_PSIZE
    self.y = self.iy * WORLD_AREA_PSIZE
    self:init_area()
    self:signal("add_object")
    self:signal("remove_object")
end

function area:init_area()
    local bgwix,bgwiy = self.ix * WORLD_AREA_SIZE,self.iy * WORLD_AREA_SIZE
    for x = 1,WORLD_AREA_SIZE do
        self.tiles[x] = {}
        for y = 1,WORLD_AREA_SIZE do
            local g = {
                tile_group = "tile_default",
                tile_name = "no_tile",
                aidxx = x,
                aidxy = y,
                widxx = bgwix + x - 1,
                widxy = bgwiy + y - 1,
            }
            self.tiles[x][y] = g
        end
    end
end

function area:fill_tiles(tile_group,tile_name)
    for x = 1,WORLD_AREA_SIZE do
        for y = 1,WORLD_AREA_SIZE do
            local tile = self.tiles[x][y]
            tile.tile_group = tile_group
            tile.tile_name = tile_name
        end
    end
end

function area:add(object)
    if self.objects[object.name] ~= nil then return end
    self.objects[object.name] = object
    self:emit_signal("add_object",object)

    if core.core_mode == CORE_MODE_SERVER then
        if oopsys.is(object,"ClientPlayer") then
            self.clients[object.name] = object
        end
    end
end

function area:remove(object)
    local name = object.name
    if self.objects[name] == nil then return end
    self.objects[name] = nil
    self.emit_signal("remove_object",object)

    if core.core_mode == CORE_MODE_SERVER then
        if oopsys.is(object,"ClientPlayer") then
            self.clients[object.name] = nil
        end
    end
end


function area:draw()
    local bx,by = self.x,self.y
    for x = 1,WORLD_AREA_SIZE do
        for y = 1,WORLD_AREA_SIZE do
            local tile = self.tiles[x][y]
            local group = core.assets.group(tile.tile_group)
            if group then
                local assets = group:get_assets(tile.tile_name)
                love.graphics.draw(assets,tile.widxx * WORLD_GRID_PSIZE,tile.widxy * WORLD_GRID_PSIZE)
            end        
        end
    end

    if DEBUG then
        love.graphics.setColor(1,0,0,1)
        love.graphics.rectangle("line",self.x,self.y,WORLD_AREA_PSIZE,WORLD_AREA_PSIZE)
        love.graphics.setColor(1,1,1,1)
    end
end

return area:reg()
